#include "widget.h"
#include "ui_widget.h"
#include <QNetworkDatagram>
#include <QMessageBox>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    setWindowTitle("服务器");
    udpsocket=new QUdpSocket(this);

    //先连接
    connect(udpsocket,&QUdpSocket::readyRead,this,&Widget::handle);
    //再绑定
    bool ret=udpsocket->bind(QHostAddress::Any,9090);
    if(!ret)
    {
        QMessageBox::critical(this,"服务器绑定失败",udpsocket->errorString());
        return;
    }


}

void Widget::handle()
{
    //获取请求
    const QNetworkDatagram& requestdatagram=udpsocket->receiveDatagram();
    QString request=requestdatagram.data();
    QNetworkDatagram responsdatagram(request.toUtf8(),requestdatagram.senderAddress(),requestdatagram.senderPort());
    udpsocket->writeDatagram(responsdatagram);
    QString text="["+requestdatagram.senderAddress().toString()+":"+QString::number(requestdatagram.senderPort())+"] "
            +request;
    ui->listWidget->addItem(text);
}

Widget::~Widget()
{
    delete ui;
}

